<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/1/24
 * Time: 14:07
 */

namespace Lm\Controllers;

use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\lm\XHLmUseMR;
use Admin\Models\sys\XhsysEnum;
use Helpers\Assets;
use Helpers\Controller;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\XhException;
use Modules\Power;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Paginator\Adapter\QueryBuilder;
use Services\Msg\Msg;

class MeetingController extends Controller
{
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
        // 这个方法会在每一个能找到的action前执行
        if (in_array(strtolower($dispatcher->getActionName()), [
            strtolower('meetingPlan'),
        ])) {
            return true;
        }
        $userId = Main::getLoginUserInfo('userId');
        if (!$userId) {
            Main::goLoginPage();
        }
    }


    /**
     * 首页
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale  20190212
     */
    public function homeAction()
    {
        if (!Power::exist('Lm_MR_UseMRList')) {
            return $this->sendViewError('没有权限');
        }
        $this->view->pick('meeting/home');
        Assets::importJs('js/meeting/home.js');
        $rooms = XhsysEnum::getEnumByNodeName('会议室');
        try {
            $dataSource = [];
            foreach ($rooms as $index => $text) {
                $data = self::getMeetingList([
                    'startTime' => date('Y-m-d'),
                    'endTime'   => date('Y-m-d', strtotime('+5 day')),
                    'order' => 'asc',
                    'sort'  => 'tStartTime',
                    'room'  => $index,
                    'fields' => ['iStaffId','sTitle','tStartTime','tEndTime','sApplyName']
                ], false);
                if (!$data) {
                    $dataSource[$index] = $data;
                    continue;
                }
                $staffIds = array_values(array_filter(array_unique(array_column($data, 'iStaffId'))));
                $staffPhone = XhhrmStaff::getStaffList([
                    'staffIds' => $staffIds,
                    'fields'   => ['iStaffId', 'sSelfPhone']
                ], false);
                $staffPhone = array_column($staffPhone, 'sSelfPhone', 'iStaffId');
                foreach ($data as &$row) {
                    $phone = Tool::getValue($staffPhone, @$row['iStaffId'], '');
                    if ($phone) {
                        $row['sApplyName'] .= "({$phone})";
                    }
                    $row['timePeriods'] = date('Y-m-d H:i', strtotime($row['tStartTime'])) . '~'
                        . date('H:i', strtotime($row['tEndTime']));
                }
                unset($row);
                $dataSource[$index] = $data;
                unset($data);
            }
            return $this->view->setVars([
                'rooms' => $rooms,
                'data'  => $dataSource
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 会议室列表
     *
     * @return string
     *
     * create by dale  20190124
     */
    public function indexAction()
    {
        if (!Power::exist('Lm_MR_UseMRList')) {
            return $this->sendViewError('没有权限');
        }
        $roomId = $this->request->getQuery('roomId', 'string');
//        $this->view->setTemplateBefore('listForm');
        $this->view->pick('meeting/index');
        Assets::easyUI();
        Assets::importJs('js/meeting/index.js');
        Template::exists('MR_Meeting', 'list') or die(Main::showMessageModal('MR_Meeting 配置文件不存在，请先创建！', 109106002));
        $listButton = $listSearchArr = [];
        if (Power::exist('Lm_MR_UseMRList_Add')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增会议', 'icon' => 'fa-plus');
        }
        if (Power::exist('Lm_MR_UseMRList_Del')) {
            $listButton[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除申请', 'icon' => 'fa-trash');
        }
        $listSearchArr[] = array('type' => 'text', 'class'  => 'easyui-datebox', 'id' => 'List_Search_StartTime',
            'label' => ' 时间段：','style'=>'width:100px;', 'value' => date('Y-m-d'));
        $listSearchArr[] = array('type' => 'text', 'class' => 'easyui-datebox', 'id' => 'List_Search_EndTime',
            'label' => ' ~ ', 'style' => 'width:100px;', 'value' =>  date('Y-m-d', strtotime('+7 day')));
        $rooms = XhsysEnum::getEnumByNodeName('会议室');
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_room', 'data' => $rooms + [0 => '请选择会议室'],
            'default' => $roomId ?: '');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search',
            'style' => 'margin-left:10px');
        $this->view->setVars([
            'List' => Template::createList('meetingList', 'MR_Meeting', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButton),
            ]),
        ]);
    }

    /**
     * 分页方法
     *
     * @param $builder
     * @param $page
     * @param $rows
     *
     * @return array
     *
     * create by dale  20190124
     */
    public static function runBuildPage($builder, $page, $rows)
    {
        $paginator = new QueryBuilder([
            'builder'   => $builder,
            'limit'     => $rows,
            'page'      => $page
        ]);
        @$paginator = $paginator->getPaginate();
        $total = $paginator->total_items;
        $rows  = $paginator->items->toArray();
        return ['total' => $total, 'rows' => $rows];
    }

    /**
     * 获取会议室列表
     *
     * @param $params
     * @param bool $needPage
     *
     * @return array
     * @throws \Exception
     *
     * create by dale  20190124
     */
    public function getMeetingList($params, $needPage = true)
    {
        $fields = Tool::getValue($params, 'fields', []);
        $key = Tool::getValue($params, 'key');
        $page = Tool::getValue($params, 'page');
        $size = Tool::getValue($params, 'size');
        $room = Tool::getValue($params, 'room');
        $startTime = Tool::getValue($params, 'startTime');
        $endTime   = Tool::getValue($params, 'endTime');
        $order     = Tool::getValue($params, 'order');
        $sort      = Tool::getValue($params, 'sort');
        $roomColumns =  array_keys(get_object_vars(new XHLmUseMR()));
        //去除私有对象
        $roomColumns = array_filter(array_map(function ($val) {
            if (strpos($val, '_') !== false) {
                return '';
            } else {
                return $val;
            }
        }, $roomColumns));
        if ($fields) {
            $roomColumns = array_intersect($roomColumns, $fields);
        }
        $roomColumns = array_map(function ($val) {
            return 'm.'.$val;
        }, $roomColumns);
        $builder =  \Helpers\Di::get()->modelsManager->createBuilder()
            ->from(['m' => 'Admin\Models\lm\XHLmUseMR'])
            ->columns(array_merge($roomColumns, []))
            ->where('m.bDelete = 0');
        if ($key) {
            $builder->andWhere('m.sApplyName like :key:', ['key' => '%'.$key.'%']);
        }
        if ($room) {
            $builder->andWhere('m.iMeetingRoom = :room:', ['room' => $room]);
        }
        if ($startTime && $endTime) {
            $builder->andWhere(
                ' :startTime: <= DATE_FORMAT(m.tEndTime,\'%Y-%m-%d\') and :endTime: >=  DATE_FORMAT(m.tStartTime,\'%Y-%m-%d\') ',
                ['startTime' => $startTime, 'endTime' => $endTime]
            );
        }
        if ($order && $sort) {
            $builder->orderBy(" {$sort} {$order} ");
        }
        if ($needPage) {
            if (!$page || !$size) {
                throw new \Exception('缺少分页参数');
            }
            $data = self::runBuildPage($builder, $page, $size);
            Tool::runEnum($data['rows'], [
                'iMeetingRoom' => XhsysEnum::getEnumByNodeName('会议室')
            ]);
        } else {
            $data = $builder->getQuery()->execute()->toArray();
            Tool::runEnum($data, [
                'iMeetingRoom' => XhsysEnum::getEnumByNodeName('会议室')
            ]);
        }
        return $data;
    }

    /**
     * 获取会议列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190124
     */
    public function getMeetingListAction()
    {
        $page = $this->request->getPost('page', 'int');
        $size = $this->request->getPost('rows', 'int');
        $key  = $this->request->getPost('key', 'string');
        $room = $this->request->getPost('room', 'int');
        $startTime = $this->request->getPost('startTime', 'string');
        $endTime = $this->request->getPost('endTime', 'string');
        $order = $this->request->getPost('order', 'string');
        $sort  = $this->request->getPost('sort', 'string');
        if (!$page || !$size) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        if (!Power::exist('Lm_MR_UseMRList')) {
            return $this->sendErrorResponse(403, '缺少权限');
        }
        try {
            $data = self::getMeetingList([
                'page' => $page,
                'size' => $size,
                'key'  => $key,
                'room' => $room,
                'startTime' => $startTime,
                'endTime' => $endTime,
                'order'=> $order ?: 'desc',
                'sort' => $sort ?: 'tCreateDate',
            ]);
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 删除会议室
     *
     * @param $id
     *
     * @return bool
     * @throws \Exception
     *
     * create by dale  20190124
     */
    public static function delMeeting($id)
    {
        if (!$id) {
            throw new \Exception('缺少参数');
        }
        $obj = XHLmUseMR::findFirst($id);
        if (!$obj) {
            throw new \Exception('未找到该记录');
        }
        $obj->bDelete = 1;
        if (!$obj->save()) {
            throw new \Exception('删除失败');
        }
        return true;
    }

    /**
     * 删除会议
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190124
     */
    public function delMeetingAction()
    {
        if (!Power::exist('Lm_MR_UseMRList_Del')) {
            return $this->sendErrorResponse(403, '缺少权限');
        }
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XHLmUseMR::findFirst($id);
        if (!$obj) {
            return $this->sendErrorResponse(400, '未找到该记录');
        }
        if ($obj->iCreateUserId != Main::getLoginUserInfo('userId')) {
            return $this->sendErrorResponse(403, '缺少权限,只有创建人才能删除');
        }
        try {
            self::delMeeting($id);
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 会议表单
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20190124
     */
    public function meetingFormAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            $this->view->pick('meeting/meetingForm');
            Assets::easyUI();
            Assets::datetimePicker();
            Assets::importJs('js/meeting/meetingForm.js');
            if (!$id) {
                $staffId = Hrm::getLoginStaffId();
                $staff = XhhrmStaff::findFirst($staffId);
                if (!$staff) {
                    throw new \Exception('未找到职工信息');
                }
                $staff = $staff->toArray();
                $staff['sDepName'] = XhhrmDepart::getFirstDepName($staff['sDepIds']);
                $staff['iDepId'] = array_values(array_filter(explode(',', $staff['sDepIds'])));
                $staff['iDepId'] = end($staff['iDepId']);
            } else {
                $info = XHLmUseMR::findFirst($id);
                if (!$info) {
                    throw new \Exception('未找到会议信息');
                }
                $info = $info->toArray();
                $this->view->setVar('info', $info);
                $power = false;
                if ($info['iCreateUserId'] == Main::getLoginUserInfo('userId')) {
                    $power = true;
                }
                $this->view->setVar('power', $power);
                $staff = [
                    'sDepName' => XhhrmDepart::getFirstDepName($info['iDepId']),
                    'sStaffName' => $info['sApplyName'],
                    'iDepId' => $info['iDepId'],
                    'iStaffId' => $info['iStaffId'],
                ];
            }
            return $this->view->setVars([
                'staff' => $staff,
                'rooms' => XhsysEnum::getEnumByNodeName('会议室'),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 保存
     *
     * @param $postData
     *
     * @return bool/string
     * @throws \Exception
     *
     * create by dale  20190128
     */
    public function saveMeeting($postData)
    {
        if (!$postData) {
            throw new \Exception('缺少参数');
        }
        $id = Tool::getValue($postData, 'iUMRId');
        $mParticipant = Tool::getValue($postData, 'mParticipant', []);
        $conFiles = Tool::getValue($postData, 'conFiles', []);
        $sumFiles = Tool::getValue($postData, 'sumFiles', []);
        $bModify = false;
        if ($id) {
            $obj = XHLmUseMR::findFirst($id);
            if (!$obj) {
                throw new \Exception('未找到该记录');
            }
            $bModify = true;
        } else {
            $obj = new XHLmUseMR();
        }
        $obj->assign($postData);
        if ($mParticipant) {
            $obj->mParticipant = implode(',', $mParticipant);
            $newArray=[];
            $participants = array_values(array_filter($mParticipant));
            foreach ($participants as $participant) {
                if (is_bool(strpos($participant, 'D-'))) {
                    $newArray[] = $participant;
                }
            }
            //去重复
            $newArray = array_values(array_filter(array_unique($newArray)));
            $obj->mUserIds = implode(',', $newArray);
        }
        if ($conFiles) {
            $obj->mConFiles = $conFiles;
        }
        if ($sumFiles) {
            $obj->mSumFiles = $sumFiles;
        }
        if (!$obj->save()) {
            throw new \Exception('保存失败');
        }
        $rooms = XhsysEnum::getEnumByNodeName('会议室');
        $str = '';
        if ($obj->bSendSms) {
            if (strtotime($obj->tEndTime) > time()) {  //未来的会议
                $staffs = Hrm::getStaffInfo($newArray);
                foreach ($staffs as $staff) {
                    $sendInfo = "您有一个关于'{$obj->sTitle}'的会议,会议时间为：{$obj->tStartTime}至{$obj->tEndTime}, "
                    . "会议地点为:会议室- {$rooms[$obj->iMeetingRoom]},请准时参加。";
                    try {
                        Main::sendSMS($staff['phoneNumber'], $sendInfo);
                    } catch (\Exception $e) {
                        $str = '短信发送失败';
                        break;
                    }
                }
            }
        }
        if ($bModify) {
            Msg::noticeOperator()->scrap('Lm', 'Meeting', $obj->iUMRId);//先废弃，再设置
        }
        $notice = Msg::noticeCreator('Lm', 'Meeting', $obj->iUMRId);
        $notice->setTitle('会议邀请')
            ->setContent("您有一个关于'{$obj->sTitle}'的会议,会议时间为：{$obj->tStartTime}至{$obj->tEndTime}, "
                . "会议地点为:会议室- {$rooms[$obj->iMeetingRoom]},请准时参加。")
            ->addReceiver(explode(',', $obj->mUserIds))
            ->setType($notice::TYPE_INFO)
            ->setViewMode($notice::VIEW_ALERT)
            ->send();
        return $str ?: true;
    }

    /**
     * 保存信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190128
     */
    public function saveMeetingAction()
    {
        try {
            $postData = $this->request->getPost();
            $bNeedSms = $this->request->getPost('bNeedSms');
            if (!$postData['tStartTime'] || !$postData['tEndTime']) {
                return $this->sendErrorResponse(400, '开始结束时间必选');
            }
            if (date('Y-m-d', strtotime($postData['tStartTime'])) != date('Y-m-d', strtotime($postData['tEndTime']))
            ) {
                return $this->sendErrorResponse(400, '会议必须当天结束');
            }
            if ($postData['iUMRId']) {
                if (!Power::exist('Lm_MR_UseMRList_Edit')) {
                    return $this->sendErrorResponse(403, '编辑权限');
                }
            } else {
                if (!Power::exist('Lm_MR_UseMRList_Add')) {
                    return $this->sendErrorResponse(403, '新增权限');
                }
            }
            if (!$postData['iMeetingRoom']) {
                return $this->sendErrorResponse(400, '必须选择一个会议室');
            }
            if (!$postData['sTitle']) {
                return $this->sendErrorResponse(400, '会议标题必填');
            }
            $rooms = $this->filterMeetRoom($postData['tStartTime'], $postData['tEndTime'], $postData['iUMRId']);
            if (!in_array($postData['iMeetingRoom'], array_keys($rooms))) {
                return $this->sendErrorResponse(400, '当前会议室已被占用');
            }
            $res = self::saveMeeting($postData);
            if (is_string($res)) {
                return $this->sendSuccessResponse('保存成功,'.$res);
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 会议安排
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     *
     * create by dale  20190125
     */
    public function meetingScheduleAction()
    {
        try {
            $room = $this->request->getQuery('room', 'string');
            $startTime = $this->request->getQuery('startTime', 'string');
            $endTime = $this->request->getQuery('startTime', 'string');
            $startTime = $startTime ?
                date('Y-m-d', strtotime($startTime)) :
                date('Y-m-d', strtotime(' -7 day'));
            $endTime = $endTime ?
                date('Y-m-d', strtotime($endTime)) :
                date('Y-m-d');
            if (!$room) {
                return $this->sendViewError('未传入会议室id');
            }
            $this->view->pick('meeting/meetingSchedule');
            Assets::importJs('js/meeting/meetingSchedule.js');
            return $this->view->setVars([
                'startTime' => $startTime,
                'endTime'   => $endTime,
                'roomName'  => Tool::getValue(XhsysEnum::getEnumByNodeName('会议室'), $room, '')
            ]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取根据时间段获取到会议室
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190125
     */
    public function getMeetingByTimeAction()
    {
        $startTime = $this->request->get('startTime', 'string');
        $endTime = $this->request->get('endTime', 'string');
        $room    = $this->request->get('room', 'string');
        $currentId = $this->request->get('currentId', 'string', '0');
        if (!$startTime || !$endTime) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        try {
            $data = self::getMeetingList([
                'startTime' => $startTime,
                'endTime'   => $endTime,
                'order' => 'desc',
                'sort'  => 'tCreateDate',
                'room'  => $room
            ], false);
            XhhrmDepart::runDepNameByDepId($data, ['iDepId' => 'sDepName'], true);
            foreach ($data as &$row) {
                $row['className'] = '';
                if ($row['iUMRId'] == $currentId) {
                    $row['className'] = 'currentStyle';
                }
            }
            unset($row);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 会议计划
     *
     * @return string
     *
     * create by dale  20190129
     */
    public function meetingPlanAction()
    {
        try {
            $roomId = $this->request->getQuery('roomId', 'string');
            if (!$roomId) {
                return $this->sendViewError('没有传入会议室id');
            }
            $this->view->pick('meeting/meetingPlan');
            Assets::importJs('js/meeting/meetingPlan.js');
            $data = self::getMeetingList([
                'startTime' => date('Y-m-d'),
                'endTime'   => date('Y-m-d'),
                'order' => 'asc',
                'sort'  => 'tStartTime',
                'room'  => $roomId,
                'fields' => ['iStaffId','sTitle','tStartTime','tEndTime','sApplyName']
            ], false);
            $staffIds = array_values(array_filter(array_unique(array_column($data, 'iStaffId'))));
            $staffPhone = XhhrmStaff::getStaffList([
                'staffIds' => $staffIds,
                'fields'   => ['iStaffId', 'sSelfPhone']
            ], false);
            $staffPhone = array_column($staffPhone, 'sSelfPhone', 'iStaffId');
            foreach ($data as &$row) {
                $phone = Tool::getValue($staffPhone, @$row['iStaffId'], '');
                if ($phone) {
                    $row['sApplyName'] .= "({$phone})";
                }
                $row['timePeriods'] = date('H:i', strtotime($row['tStartTime'])) . '~'
                    . date('H:i', strtotime($row['tEndTime']));
            }
            unset($row);
//            var_dump($data);die;
            return $this->view->setVars([
                'data' => $data,
                'day'  => date('Y-m-d'),

            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 文件上传
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190128
     */
    public function uploadFileAction()
    {
        try {
            if (!$this->request->hasFiles()) {
                return $this->sendErrorResponse(500, '没有文件上传');
            }
            $file = $this->request->getUploadedFiles()[0];
            if (!$file->getName()) {
                return $this->sendErrorResponse(500, '没有文件上传');
            }
            $fileName = md5_file($file->getTempName()) . '.' . $file->getExtension();
            $filePath = TEMP_PATH . '/'.$fileName;
            $file->moveTo($filePath);

            $url = Main::uploadFileToOSS($filePath, 'file');
            unlink($filePath);
            $returnArray=[
                "fileName" => $file->getName(),
                "url" =>  $url,
            ];
            return $this->sendJsonResponse($returnArray, true);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 申请会议室
     *
     * @param $startTime
     * @param $endTime
     * @param $currentId
     *
     * @return array|bool
     *
     * create by dale  20190218
     */
    public function filterMeetRoom($startTime, $endTime, $currentId)
    {
        $rooms = XhsysEnum::getEnumByNodeName('会议室');
        if (strtotime($endTime) < time()) { //之前的申请，不做限制
            return $rooms;
        } else { //结束时间比当前时间晚，需要做会议室的限制
            $sql = "select iMeetingRoom from XHLm_UseMR where bDelete = 0 and
                        '{$startTime}' <= tEndTime and '{$endTime}' >= tStartTime ";
            if ($currentId) {
                $sql .= " and iUMRId != {$currentId} ";
            }
            $data = $this->db->fetchAll($sql);
            if ($data) {
                $data = array_values(array_filter(array_unique(array_column($data, 'iMeetingRoom'))));
                foreach ($rooms as $index => $row) {
                    if (in_array($index, $data)) {
                        unset($rooms[$index]);
                    }
                }
            }
            return $rooms;
        }
    }

    /**
     * 过滤当前时间段不可申请的会议室
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190129
     */
    public function filterMeetRoomAction()
    {
        try {
            $startTime = $this->request->getPost('startTime', 'string');
            $endTime   = $this->request->getPost('endTime', 'string');
            $currentId = $this->request->getPost('currentId', 'string');
            if (!$startTime || !$endTime) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            if (strtotime($startTime) > strtotime($endTime)) {
                return $this->sendErrorResponse(400, '开始时间不能大于结束时间');
            }
            $rooms = $this->filterMeetRoom($startTime, $endTime, $currentId);

            return $this->sendJsonResponse($rooms);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 获取 职工部门树
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190128
     */
    public function getDepStaffAction()
    {
        try {
            return $this->sendJsonResponse(XhhrmStaff::getDepStaff(0, true, false, true));
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 会议日历
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20190218
     */
    public function meetingCalendarAction()
    {
        try {
            $this->view->pick('meeting/meetingCalendar');
            Assets::FullCalendar();
            Assets::importJs('js/meeting/meetingCalendar.js');
            return $this->view->setVars([
                'rooms' => XhsysEnum::getEnumByNodeName('会议室'),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 申请会议室
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20190218
     */
    public function getCalendarAction()
    {
        try {
            $startTime = $this->request->getPost('startDay', 'string');
            $endTime   = $this->request->getPost('endDay', 'string');
            $room      = $this->request->getPost('room', 'int');
            if (!$startTime || !$endTime || !$room) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $data = self::getMeetingList([
                'startTime' => date('Y-m-d', strtotime($startTime)),
                'endTime'   => date('Y-m-d', strtotime($endTime)),
                'order' => 'asc',
                'sort'  => 'tStartTime',
                'room'  => $room,
                'fields' => ['iStaffId','sTitle','tStartTime','tEndTime','sApplyName']
            ], false);
            $staffIds = array_values(array_filter(array_unique(array_column($data, 'iStaffId'))));
            $staffPhone = XhhrmStaff::getStaffList([
                'staffIds' => $staffIds,
                'fields'   => ['iStaffId', 'sSelfPhone']
            ], false);
            $staffPhone = array_column($staffPhone, 'sSelfPhone', 'iStaffId');
            foreach ($data as &$row) {
                $phone = Tool::getValue($staffPhone, @$row['iStaffId'], '');
                if ($phone) {
                    $row['sPhone'] = $phone;
                }
            }
            unset($row);
            $dealData = [];
            foreach ($data as $row) {
                $dealData[] = [
                    'start' => $row['tStartTime'],
                    'end'   => $row['tEndTime'],
                    'title' => "{$row['sTitle']}({$row['sApplyName']})",
                    'extraData' => $row
                ];
            }
            return $this->sendJsonResponse($dealData);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }





//    public function testAction()
//    {
//        $arr = [1,1,2,3,3,3,5,5,6,6,7,3];
//        $newArr = [];
//        foreach ($arr as $index => $val) {
//            if ($index == 0) {
//                $newArr[] = $val;
//                continue;
//            }
//            if ($val == end($newArr)) {
//                continue;
//            } else {
//                $newArr[] = $val;
//            }
//        }
//        var_dump($newArr);die;
//    }







}